<template>
  <div>
    <div class="fh-login">
      <div class="fh-login-left">
        <!-- <h2 style="padding-bottom: 0px">品讯</h2> -->
        <h2 style="padding-bottom: 0px">{{ logo }}</h2>
        <h2 style="font-size:30px">工厂仓储管理系统</h2>
      </div>
      <div class="fh-login-right">
        <div class="login-title">欢迎使用</div>
        <a-form
          id="formLogin"
          ref="formLogin"
          :form="form"
          class="login-form"
          @submit="handleSubmit">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="请输入账户"
              class="login-input"
              style="margin-top:40px"
              v-decorator="[
                'username',
                {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input
              size="large"
              type="password"
              autocomplete="false"
              placeholder="请输入密码"
              class="login-input"
              max="6"
              v-decorator="[
                'password',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-checkbox :checked="remberMe" v-model="remberMe">记住密码</a-checkbox>
          </a-form-item>
          <a-form-item>
            <a-button class="btn" type="primary" htmlType="submit">
              登录
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getSmsCaptcha, checkCaptchaCode, getLogo } from '@/api/upms/login'
import { encryptPassword } from '@/common/common'
import cookie from 'vue-cookie'
import BaseTool from '@/utils/tool'

export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      randomStr: '',
      captchaImage: null,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      remberMe: null,
      password: null,
      logo: ''
    }
  },
  created () {
    // get2step({ })
    //   .then(res => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    // this.requiredTwoStepCaptcha = true
    // 获取用户名和密码
    let username = cookie.get('username')
    if (BaseTool.Object.isBlank(username)) {
      username = ''
    }
    const password = cookie.get('password')
    console.log(username, password, 33333)
    this.remberMe = this.getRemberMe()
    const { form: { setFieldsValue } } = this
    this.$nextTick(() => {
      setFieldsValue({
        username: username,
        password
      })
    })
    this.getCaptchaImage()
    getLogo().then(res => {
      console.log(res)
      this.logo = res.data
    })
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password', 'captchaCode'] : ['mobile', 'smsCode', 'captchaCode']
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = {
            ...values,
            randomStr: this.randomStr,
            password: values.password ? encryptPassword(values.password) : '',
            grant_type: 'password',
            scope: 'server',
            loginType: customActiveKey === 'tab1' ? 1 : 2
          }
          // 记住密码的时候直接使用cookie中的密码
          if (values.password === cookie.get('password')) {
            loginParams.password = cookie.get('password')
          }
          this.password = loginParams.password
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'username'] = values.username
          // loginParams.password = md5(values.password)
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => console.log(err))
            .finally(() => {
              state.loginBtn = false
              this.getCaptchaImage()
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['mobile', 'captchaCode'], { force: true }, (err, values) => {
        if (!err) {
          checkCaptchaCode({ captchaCode: values.captchaCode, randomStr: this.randomStr }).then(res => {
            const flag = res.data
            if (flag) {
              state.smsSendBtn = true

              const interval = window.setInterval(() => {
                if (state.time-- <= 0) {
                  state.time = 60
                  state.smsSendBtn = false
                  window.clearInterval(interval)
                }
              }, 1000)

              const hide = this.$message.loading('验证码发送中..', 0)
              getSmsCaptcha({ mobile: values.mobile, captchaCode: values.captchaCode, randomStr: this.randomStr }).then(res => {
                setTimeout(hide, 2500)
                this.$notification['success']({
                  message: '提示',
                  description: '验证码获取成功，您的验证码为：' + res.data,
                  duration: 8
                })
              }).catch(err => {
                setTimeout(hide, 1)
                clearInterval(interval)
                state.time = 60
                state.smsSendBtn = false
                this.requestFailed(err)
              })
            } else {
              this.$message.error('图片验证码错误')
              this.getCaptchaImage()
            }
          })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      this.$router.push({ path: '/WorkplaceBacklog' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
      // 记住密码
      cookie.set('remberMe', this.remberMe, 7)
      cookie.set('username', this.form.getFieldValue('username'), 7)
      if (this.remberMe) {
        cookie.set('password', this.password, 7)
      } else {
        cookie.delete('password')
      }
    },
    requestFailed (err) {
      console.log(err)
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    getCaptchaImage () {
      this.randomStr = this.getRandomStr()
      // this.captchaImage = location.protocol + '//' + location.host + '/api/verify/captcha/' + this.randomStr
      this.captchaImage = process.env.VUE_APP_API_BASE_URL + '/verify/captcha/' + this.randomStr
      // getCaptchaImage(this.randomStr).then(res)
    },
    getRandomStr () {
      return new Date().getTime() + Math.random() * 1000
    },
    remberPassword (param) {
      console.log(param)
    },
    getRemberMe () {
      const remberMe = cookie.get('remberMe')
      if (BaseTool.Object.isBlank(remberMe)) {
        return true
      } else {
        return remberMe === 'true'
      }
    }
  }
}
</script>

<style scoped>
  .fh-login {
    width: 830px;
    height: 435px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -250px;
    margin-left: -440px;
    background: url('~@/assets/logn.png') no-repeat;
  }
  .fh-login .fh-login-left {
    float: left;
    width: 50%;
  }
  .fh-login .fh-login-left img {
    margin: 132px auto 0;
    display: block;
  }
  .fh-login .fh-login-left h2 {
    margin-top: 65px;
    margin-left: 8%;
    padding-bottom: 20px;
    color: #ffffff;
    font-size: 40px;
    font-weight: 600;
    text-align: center;
  }
  .fh-login .fh-login-right {
    float: right;
    width: 48%;
  }
  .fh-login-right .login-title {
    font-size: 24px;
    color: #333;
    padding: 15px 0px;
    border-bottom: 1px solid #ccc;
    text-align: center;
  }
  .fh-login .btn {
    display: inline-block;
    color: #FFF !important;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25) !important;
    border: 5px solid #FFF;
    border-radius: 0;
    box-shadow: none !important;
    -webkit-transition: background-color 0.15s, border-color 0.15s, opacity 0.15s;
    -o-transition: background-color 0.15s, border-color 0.15s, opacity 0.15s;
    transition: background-color 0.15s, border-color 0.15s, opacity 0.15s;
    cursor: pointer;
    vertical-align: middle;
    width: 83%;
    height: 52px;
    border: none;
    margin-top:15px;
    margin-left: 12px;
    background: rgb(82, 166, 212) !important;
    color: rgb(255, 255, 255);
    user-select: none;
  }
  .fh-login .login-input{
    border: none!important;
    outline: none!important;
    background-color: #fff!important;
    height: 42px!important;
    width: 87%!important;
    /*margin-left: 35px;*/
  }
  /*设置输入图标大小*/
  .ant-input-affix-wrapper{
    font-size: 24px;
  }
  .login-form{
    margin-left: 35px;
  }
  /*调整图标位置*/
  .login-form .ant-input-affix-wrapper .ant-input-prefix {
    left: 9px !important;
  }
  .login-form .ant-input-affix-wrapper .ant-input:not(:first-child){
    padding-left: 38px;
  }
</style>
